package cn.cena._05topics;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer2 {

    // 队列名
    public static final String NAME_QUEUE_TOPICS3 = "NAME_QUEUE_TOPICS3";

    public static void main(String[] args) throws IOException, TimeoutException {

        // 获取连接
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();

        // 获取通道
        final Channel channel = connection.createChannel();
        // 创建队列
        // 参数1：队列名，参数2：持久化，参数3：是否独占通道，参数4：使用后摧毁，参数5：参数
        channel.queueDeclare("NAME_QUEUE_TOPICS3", true, false, false, null);

        // 绑定队列
        // 参数1：队列名 参数2：交换机名，参数3：routingkey
        channel.queueBind(NAME_QUEUE_TOPICS3, Pruducer.NAME_EXCHANGE_TOPICS, "info.#");

        // 处理消息
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                System.out.println("consumerTag:"+ consumerTag);
                System.out.println("交换机："+envelope.getExchange());
                System.out.println("消息id："+envelope.getDeliveryTag());
                System.out.println("队列"+envelope.getRoutingKey());
                System.out.println(new String(body));

                // 手动确认消息 参数1，消息id，  参数2：是否确认多条消息
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        // 监听队列
        channel.basicConsume(NAME_QUEUE_TOPICS3,consumer);
    }
}
